package com.zky.gulimall.order.listener;

import com.rabbitmq.client.Channel;
import com.zky.gulimall.order.entity.OrderEntity;
import com.zky.gulimall.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description 订单关闭监听
 * @Author 张开源
 * @Date 2022/12/16 17:55
 * @Version 1.0
 **/
@Component
@RabbitListener(queues = "order.release.order.queue")
@Slf4j
public class OrderCloseListener {
    @Autowired
    private OrderService orderService;

    private static int retryCount = 0;

    /**
     * 手动确认,失败重试需要接受到异常信息,如果必须要try catch 操作,需要在catch里，把异常抛出去，ack拒绝重新入队不能解决无限重试问题。
     *
     * @param orderEntity
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    public void closeOrder(OrderEntity orderEntity, Channel channel, Message message) throws IOException {
        try {
            log.warn("收到过期订单信息，准备关闭订单，订单信息：{}", orderEntity);
            //有订单状态，能防止消息重复投递
            orderService.closeOrder(orderEntity);
            //可以做支付宝手动收单，暂时不做，参考支付宝支付demo  alipay.trade.close.jsp
            ////获得初始化的AlipayClient
            //	AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
            //
            //	//设置请求参数
            //	AlipayTradeCloseRequest alipayRequest = new AlipayTradeCloseRequest();
            //	//商户订单号，商户网站订单系统中唯一订单号
            //	String out_trade_no = new String(request.getParameter("WIDTCout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //	//支付宝交易号
            //	String trade_no = new String(request.getParameter("WIDTCtrade_no").getBytes("ISO-8859-1"),"UTF-8");
            //	//请二选一设置
            //
            //	alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," +"\"trade_no\":\""+ trade_no +"\"}");
            //
            //	//请求
            //	String result = alipayClient.execute(alipayRequest).getBody();
            //
            //	//输出
            //	out.println(result);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            retryCount=0;
            log.warn("手动确认消息完毕------------------------------------ack 确认");
        } catch (IOException e) {
            log.error("收到过期订单信息，准备关闭订单，关闭出现异常,orderEntity：{},e:", orderEntity, e.getLocalizedMessage());
            if (retryCount >= 3) {
                //记录消息数据表，后续补偿拒绝不再入队
                retryCount = 0;
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
            retryCount++;
            throw new RuntimeException("收到过期订单信息，准备关闭订单，关闭出现异常,msg:" + e.getLocalizedMessage());
            //channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            //log.warn("订单关单手动确认消息完毕------------------------------------ack 拒绝");
        }

    }
}
